// pages/order/orderInfo/orderInfo.js
import config from '../../../utils/config'
import utils from '../../../utils/util'
import {
  orderModel
} from '../../../models/order';
const order = new orderModel();
import Dialog from '../../../vant/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '订单详情',
      //  导航栏 中间的标题
    },
    config: config,
    id: '',
    type: '', // 0 订单列表，1 批量改单
    detail: '',
    orderTotalMoney: '', // 改单前的价格
    orderTotalMoney1: '', // 改单后的价格

    date: '',//默认起始时间  
    date1: '',//默认结束时间 
    minDate: new Date().getTime(),
    // minDate1: new Date().getTime(),
    maxDate: 0,
    // maxDate1: 0,
    currentDate: new Date().getTime(), 
    // currentDate1: 0, 
    formatter(type, value) {
      if (type === 'seconds') {
        return '';
      }
      return value;
    },
    show: false,
    // show1: false,
    
    pprice: '',
    pcount: '',
    show2: false,
    pindex: 0,
    sindex: 0,
    isUnit: 0, // 是否允许小数 0否，1是

    // 可改单
    modifyTotal: 0, // 合计
    modifyTotalCount: 0, // 总数

    // 改单前
    orderTotalCount: 0, // 总数

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var id = options.id
    var type = options.type
    var nowDate = new Date()
    var year = nowDate.getFullYear()
    var mouth = nowDate.getMonth()+1
    var day = nowDate.getDate()
    // var currentDate1 =  new Date().getTime()+86400000
    var maxDate = new Date(year,(mouth+1),day).getTime()
    this.setData({
      id: id,
      type: type,
      // currentDate1: currentDate1,
      maxDate: maxDate,
      // maxDate1: maxDate
    })

    // type=1,2从报价tab页面进来的，记录上一页面点击进来的下标，方便返回的时候刷新这条数据
    this.pageindex = options.pageindex?options.pageindex:null

    this.getDetail() // 订单详情
  },
  // 订单详情
  getDetail(){
    order.orderFindById({
      shopOrderNo: this.data.id
    }, res => {
      var canteenSingleOrderGroupWithGoodInfoVoList = JSON.stringify(res.data.canteenSingleOrderGroupWithGoodInfoVoList)
      canteenSingleOrderGroupWithGoodInfoVoList = JSON.parse(canteenSingleOrderGroupWithGoodInfoVoList)

      this.setData({
        detail: res.data,
        canteenSingleOrderGroupWithGoodInfoVoList: canteenSingleOrderGroupWithGoodInfoVoList
      })
      this.allTotalFun() // 重新计算合计
    })
  },
  // 原订单表格的展开
  onSlide(e) {
    var index = e.currentTarget.dataset.trindex
    var canteenSingleOrderGroupWithGoodInfoVoList = this.data.canteenSingleOrderGroupWithGoodInfoVoList
    canteenSingleOrderGroupWithGoodInfoVoList[index].show = !canteenSingleOrderGroupWithGoodInfoVoList[index].show
    this.setData({
      canteenSingleOrderGroupWithGoodInfoVoList: canteenSingleOrderGroupWithGoodInfoVoList
    })

  },
  // 改单后表格的展开
  onSlide1(e) {
    var index = e.currentTarget.dataset.trindex
    var canteenSingleOrderGroupWithGoodInfoVoList = this.data.canteenSingleOrderGroupWithGoodInfoVoList
    canteenSingleOrderGroupWithGoodInfoVoList[index].show1 = !canteenSingleOrderGroupWithGoodInfoVoList[index].show1
    this.setData({
      canteenSingleOrderGroupWithGoodInfoVoList: canteenSingleOrderGroupWithGoodInfoVoList
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  // 预计发货时间  
  onDeliveryTime(e) {
    this.setData({
      show: true
    })
  },
  onConfirm(event) {
    var date = utils.formatTimeTwo(event.detail,'Y-M-D h:m')
    var minDate1 = event.detail

    this.setData({
      currentDate: event.detail,
      date: date,
      show: false,
      // minDate1: minDate1
    });
  },
  onCancel0(){
    this.setData({
      show: false
    })
  },
  // 预计到达时间
  // onArriveTime(e) {
  //   this.setData({
  //     show1: true
  //   })

  // },
  // onConfirm1(event) {
  //   var date1 = utils.formatTimeTwo(event.detail,'Y-M-D h:m')
  //   this.setData({
  //     currentDate1: event.detail,
  //     date1: date1,
  //     show1: false,
  //     maxDate: event.detail
  //   });
  // },
  // onCancel1(){
  //   this.setData({
  //     show1: false
  //   })
  // },

  
  // 操作/改单
  onPrice(e){
    this.data.pindex = e.currentTarget.dataset.index
    this.data.sindex = e.currentTarget.dataset.sindex
    this.data.isUnit = e.currentTarget.dataset.unit // 是否允许小数
    var canteenSingleOrderGroupWithGoodInfoVoList = this.data.canteenSingleOrderGroupWithGoodInfoVoList
    // var pprice = goodsList[index].price
    var pcount = canteenSingleOrderGroupWithGoodInfoVoList[this.data.pindex].singleOrderInfoVoList[this.data.sindex].goodCount
    this.setData({
      pcount: pcount,
      show2: true
    })
  },
  onPPrice(e){
    this.setData({
      pprice: e.detail
    })
  },
  onPCount(e){
    this.setData({
      pcount: e.detail
    })
  },
  onCancel2(){
    this.setData({
      show2: false
    })
  },
  // 订单数量确定修改
  onConfirm2(event){
    // console.log(event)
    // if(!this.data.pprice){
    //   utils.msg('请输入单价')
    //   return
    // }
    if(!this.data.pcount){
      utils.msg('请输入数量')
      event.detail.dialog.stopLoading(); // 可以通过 stopLoading() 在外部关闭按钮的 loading
      return
    }
    var canteenSingleOrderGroupWithGoodInfoVoList = this.data.canteenSingleOrderGroupWithGoodInfoVoList
    // canteenSingleOrderGroupWithGoodInfoVoList[this.data.pindex].price = this.data.pprice
    canteenSingleOrderGroupWithGoodInfoVoList[this.data.pindex].singleOrderInfoVoList[this.data.sindex].goodCount = this.data.pcount
    this.setData({
      canteenSingleOrderGroupWithGoodInfoVoList: canteenSingleOrderGroupWithGoodInfoVoList,
      show2: false
    })
    this.allTotalFun() // 重新计算合计
  },
  // 重新计算合计(可改单)
  allTotalFun() {
    var canteenSingleOrderGroupWithGoodInfoVoList = this.data.canteenSingleOrderGroupWithGoodInfoVoList
    var modifyTotal = 0, modifyTotalCount = 0, orderTotalCount = 0
    for(var p=0;p<canteenSingleOrderGroupWithGoodInfoVoList.length;p++){
        for(var k=0;k<canteenSingleOrderGroupWithGoodInfoVoList[p].singleOrderInfoVoList.length;k++){
          modifyTotal += Number(canteenSingleOrderGroupWithGoodInfoVoList[p].singleOrderInfoVoList[k].goodCount) * Number(canteenSingleOrderGroupWithGoodInfoVoList[p].singleOrderInfoVoList[k].price)
          modifyTotalCount += Number(canteenSingleOrderGroupWithGoodInfoVoList[p].singleOrderInfoVoList[k].goodCount)
          orderTotalCount += Number(canteenSingleOrderGroupWithGoodInfoVoList[p].singleOrderInfoVoList[k].originalGoodCount?canteenSingleOrderGroupWithGoodInfoVoList[p].singleOrderInfoVoList[k].originalGoodCount:canteenSingleOrderGroupWithGoodInfoVoList[p].singleOrderInfoVoList[k].goodCount)
        }
    }
    if(this.data.detail.updateStatus == 1){ // 可改单，改单前的总数
      this.setData({
        orderTotalCount: orderTotalCount
      })
    }
    this.setData({
      modifyTotal: modifyTotal,
      modifyTotalCount: modifyTotalCount
    })
  },


  // 取消订单
  onCancel: utils.throttle(function (e) {
    var _this = this
    Dialog.confirm({
      message: '是否已和买家取得联系并取消订单！'
    }).then(() => {
      // on confirm
      order.orderCancel({
        shopOrderNo: this.data.id
      }, res => {
        utils.msg('操作成功')
        // 0 订单列表，1 批量改单
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 2];
        if(_this.data.type == 0){
          // 设置上一页不在onShow的时候重新加载数据，在本页设置刷新列表
          prevPage.data.fLoad = true
          var orderList = prevPage.data.orderList
          orderList[_this.pageindex].filterUpdateOrderStatus = 10
          // console.log(orderList)
          // 修改这条数据
          prevPage.setData({
            orderList: orderList
          })
        }else if(_this.data.type == 1) {
          // 删除批量改单列表的这条数据
          // 设置上一页不在onShow的时候重新加载数据，在本页设置刷新列表
          prevPage.data.fLoad = true
          var orderList = prevPage.data.orderList
          orderList.splice(_this.pageindex, 1)
          // 修改这条数据
          prevPage.setData({
            orderList: orderList
          })
        }
        wx.navigateBack()
      })
    }).catch(() => {
      // on cancel
    });
  }),

  // 接单,发货
  onSubmit: utils.throttle(function (e) {
    var _this = this
    var allValue = e.detail.value
    if(this.data.detail.orderStatusVo.filterUpdateOrderStatus==4){ // 接单
      if(!this.data.date){
        utils.msg('请选择预计发货时间')
        return
      }
      // if(!this.data.date1){
      //   utils.msg('请选择预计到达时间')
      //   return
      // }
      var supplierAcceptOrderParamsList = []
      if(this.data.detail.updateStatus == 0){ // 可改单
        if(JSON.stringify(this.data.detail.canteenSingleOrderGroupWithGoodInfoVoList) != JSON.stringify(this.data.canteenSingleOrderGroupWithGoodInfoVoList)){ // 判断是否改单了
          for(var i=0;i<this.data.canteenSingleOrderGroupWithGoodInfoVoList.length;i++){
            var a = {
              goodCount: this.data.canteenSingleOrderGroupWithGoodInfoVoList[i].goodCount,
              goodPrice: this.data.canteenSingleOrderGroupWithGoodInfoVoList[i].price,
              goodId: this.data.canteenSingleOrderGroupWithGoodInfoVoList[i].goodId,
              shopOrderNo: this.data.id
            }
            supplierAcceptOrderParamsList.push(a)
          }
        }
      }
      order.orderAcceptl(JSON.stringify({
        shopOrderNo: this.data.id,
        predictDeliveryTime: this.data.date+':00',
        // predictArriveTime: this.data.date1+':00',
        shopRemarks: allValue.shopRemarks,
        supplierAcceptOrderParamsList: supplierAcceptOrderParamsList
      }), res => {
        utils.msg('操作成功')
        if(_this.data.type == 1){
          let pages = getCurrentPages();
          let prevPage = pages[pages.length - 2];
          prevPage.setData({
            allPage: 0, // 所有页数
            page: 1, // 第几页
            endFlag: false, // 是否到最后
            orderList: [], // 商品列表
          })
          prevPage.getList()

        }
        wx.navigateBack()
      })
    }else if(this.data.detail.orderStatusVo.filterUpdateOrderStatus==5){ // 发货
      order.orderSend({
        shopOrderNo: this.data.id,
        shopRemarks: allValue.shopRemarks
      }, res => {
        setTimeout(function(){
          utils.msg('操作成功',1500,function(){
            setTimeout(function(){
              if(_this.data.type == 1){
                let pages = getCurrentPages();
                let prevPage = pages[pages.length - 2];
                prevPage.setData({
                  allPage: 0, // 所有页数
                  page: 1, // 第几页
                  endFlag: false, // 是否到最后
                  orderList: [], // 商品列表
                })
                prevPage.getList(false)
              }
              wx.navigateBack()
            },500);
          })
        },400)
      })
    }
  }),

  // 修改订单
  onModify: utils.throttle(function (e) {
    const _this = this
    const params = {
      goodList: [],
      shopOrderNo: this.data.id
    }
    let oldData = []
    for(const iold of this.data.detail.canteenSingleOrderGroupWithGoodInfoVoList){
      for(const jold of iold.singleOrderInfoVoList){
        oldData.push(jold.goodCount)
      }
    }
    let newData = []
    for(const inew of this.data.canteenSingleOrderGroupWithGoodInfoVoList){
      for(const jnew of inew.singleOrderInfoVoList){
        newData.push(jnew.goodCount)
      }
    }
    // console.log(JSON.stringify(oldData) !== JSON.stringify(newData))
    if(JSON.stringify(oldData) !== JSON.stringify(newData)){ // 判断是否改单了
      for(const i of this.data.canteenSingleOrderGroupWithGoodInfoVoList){
        for(const j of i.singleOrderInfoVoList){
          params.goodList.push({
            goodCount: j.goodCount,
            goodId: j.goodId,
            stallId: j.stallId
          })
        }
      }
    }else{
      utils.msg('未修改信息');
      return;
    }
    order.updateOrderInfo(JSON.stringify(params),function(res){
      setTimeout(function(){
        utils.msg('操作成功',1500,function(){
          setTimeout(function(){
            if(_this.data.type == 1){
              let pages = getCurrentPages();
              let prevPage = pages[pages.length - 2];
              prevPage.setData({
                allPage: 0, // 所有页数
                page: 1, // 第几页
                endFlag: false, // 是否到最后
                orderList: [], // 商品列表
              })
              prevPage.getList(false)
            }
            wx.navigateBack()
          },500);
        })
      },400)
    })
  }),

  // 商品详情
  onLink: utils.throttle(function (e) {
    var id = e.currentTarget.dataset.productid
    wx.navigateTo({
      url: '/pages/index/commodityInfo/commodityInfo?id=' + id,
    })
  }),

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    // 设置上一页不在onShow的时候重新加载数据，在本页设置刷新列表
    prevPage.data.fLoad = true
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})